<?php

namespace app\common\model\mycurrency;

use addons\mycurrency\library\Common;
use addons\mycurrency\library\WechatTransfer;
use app\common\model\User;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

class Payment extends Model
{

    //use SoftDelete;


    // 表名
    protected $name = 'mycurrency_payment';

    const WIHDRAWAL_TYPE_DAILISHANGTIXIAN = 1;//提现类型 = 代理商收益提现
    const WIHDRAWAL_TYPE_FENXIAOSHOUYI = 2;//提现类型 = 分销佣金收益提现


    const PAY_TYPE_WEIXIN = 1;//打款类型 = 微信
    const PAY_TYPE_ZHIFUBAO = 2;//打款类型 = 支付宝

    const STATE_SHIBAI = -1;//打款状态 = 打款失败
    const STATE_WEIDAKUAN = 1;//打款状态 = 未打款
    const STATE_DAKUANZHONG = 2;//打款状态 = 打款中
    const STATE_YIDAKUAN = 3;//打款状态 = 已打款

    /**
     * 生成支付单单号
     * @return string
     */
    public static function getOrderSn()
    {
        $payOrderSn = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('ordersn', $payOrderSn)->value('id');
        if (!$exists) {
            return $payOrderSn;
        }
        return self::getOrderSn();
    }

    /**
     * 添加打款记录
     * @param int $withdrawal_type 提现类型
     * @param int $user_id 收款用户id【用户达到某个用户的微信或支付宝上】
     * @param int $withdrawal_amount 打款金额
     * @param int $pay_type 打款类型:1=微信,2=支付宝
     * @param array $data 数据
    */
    public static function increase($withdrawal_type,$user_id,$withdrawal_amount,$pay_type,$data = []){
        $insertData = [
            'ordersn' => self::getOrderSn(),
            'withdrawal_type' => $withdrawal_type,
            'user_id' => $user_id,
            'withdrawal_amount' => $withdrawal_amount,
            'pay_type' => $pay_type,
            'state' => self::STATE_WEIDAKUAN,
            'createtime' => time(),
        ];

        $insertData = array_merge($insertData,$data);
        $payment = self::create($insertData);
        self::launchPayment($payment->id);
    }

    /**
     * 调用打款接口
     * @param int $payment_id 打款记录id
    */
    public static function launchPayment($payment_id){
        $payment = self::get($payment_id);
        if(!$payment){
            throw new Exception('打款记录不存在');
            return false;
        }
        if($payment['state'] != self::STATE_WEIDAKUAN){
            throw new Exception('非未打款状态');
            return false;
        }
        $user = User::get($payment['user_id']);
        $desc = '';
        if($payment['withdrawal_type'] == self::WIHDRAWAL_TYPE_DAILISHANGTIXIAN){
            $desc = '代理商收益提现';
        }elseif ($payment['withdrawal_type'] == self::WIHDRAWAL_TYPE_FENXIAOSHOUYI){
            $desc = '用户分销收益提现';
        }
        //调用打款接口 【微信未测试 支付宝未实现】
        if($payment['pay_type'] == self::PAY_TYPE_WEIXIN){//微信打款
            $wxchar = new WechatTransfer();
            $res = $wxchar->transfer($payment['ordersn'],$user['wechat_open_id'],$wxchar['withdrawal_amount'],$desc);
            if($res['code'] == 0){//提交打款申请成功
                //记录接口反馈数据
                $payment->wechat_interface_return = json_encode($res['data']);
                //查询打款微信转账进度
                $queue_default = config('queue.default');
                Queue::later(60, "addons\mycurrency\controller\job\Payment\cashwithdrawal", ['payment_id' => $payment['id']], $queue_default);
            }else{//提交打款申请失败
                $payment->state = self::STATE_SHIBAI;
                $payment->fail_reason = $res['msg'];
                $payment->failtime = time();
                $payment->save();
                throw new Exception('转账失败，原因:'.$res['msg']);
                return false;
            }
        }elseif($payment['pay_type'] == self::PAY_TYPE_ZHIFUBAO){//支付宝打款

        }
        //修改打款记录状态
        $payment->state = self::STATE_DAKUANZHONG;
        $payment->starttime = time();
        $payment->save();

    }


}
